package cn.com.infcn.monitor.task.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.List;

import org.apache.log4j.Logger;

import cn.com.infcn.monitor.bean.IFCJVMMemoryPool;
import cn.com.infcn.monitor.bean.IFCJVMMemoryUsage;
import cn.com.infcn.monitor.task.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;

/**
 * 内存池的管理接口。
 * 内存池表示由 Java 虚拟机管理的内存资源，由一个或多个内存管理器对内存池进行管理。 
 * @author jijs
 *
 */
public class JVMMemoryPoolTask implements BaseTask {

	private static final Logger LOGGER = Logger.getLogger(JVMMemoryPoolTask.class);

	@Override
	public IFCJVMMemoryPool execute() throws Exception {
		return jvmMemoryPool();
	}

	public IFCJVMMemoryPool jvmMemoryPool() {
		MemoryUsage usage = null;
		IFCJVMMemoryUsage ifcMemoryUsage = null;


		try {
			IFCJVMMemoryPool jvmMemoryPool = new IFCJVMMemoryPool();
			
			List<MemoryPoolMXBean> memoryPoolMXBeanList = ManagementFactory.getMemoryPoolMXBeans();
			if(memoryPoolMXBeanList!=null && memoryPoolMXBeanList.size()>0){
				for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeanList) {
					ifcMemoryUsage = new IFCJVMMemoryUsage();
					String name = memoryPoolMXBean.getName();
					usage = memoryPoolMXBean.getCollectionUsage();
					if(usage == null){
						continue;
					}
					IFCBeanUtils.copyProperties(usage, MemoryUsage.class, ifcMemoryUsage);
					if (name.indexOf("Eden Space") != -1) {
						jvmMemoryPool.setEdenMemoryUsage(ifcMemoryUsage);
					} else if (name.indexOf("Survivor Space") != -1) {
						jvmMemoryPool.setSurvivorMemoryUsage(ifcMemoryUsage);
					} else if (name.indexOf("Code Cache") != -1) {
						jvmMemoryPool.setCodeCacheMemoryUsage(ifcMemoryUsage);
					} else if (name.indexOf("Perm Gen") != -1) {
						jvmMemoryPool.setPermGenMemoryUsage(ifcMemoryUsage);
					} else if (name.indexOf("Old Gen") != -1) {
						jvmMemoryPool.setOldGenMemoryUsage(ifcMemoryUsage);
					} else if (name.indexOf("Metaspace") !=-1){
						jvmMemoryPool.setMetaspaceMemoryUsage(ifcMemoryUsage);
					}
				}
			}
			return jvmMemoryPool;
		} catch (Exception e) {
			LOGGER.warn(e.getMessage(), e);
		}
		return null;
	}

	public static void main(String[] args) {
		JVMMemoryPoolTask task = new JVMMemoryPoolTask();
		IFCJVMMemoryPool jvmMemoryPool = task.jvmMemoryPool();;

//		IFCJVMMemoryUsage metaspaceMemoryUsage = jvmMemoryPool.getMetaspaceMemoryUsage();
//		System.out.println(metaspaceMemoryUsage);
		IFCJVMMemoryUsage edenspaceMemoryUsage = jvmMemoryPool.getEdenMemoryUsage();
		System.out.println(edenspaceMemoryUsage);
		IFCJVMMemoryUsage survivorspaceMemoryUsage = jvmMemoryPool.getSurvivorMemoryUsage();
		System.out.println(survivorspaceMemoryUsage);
		IFCJVMMemoryUsage oldspaceMemoryUsage = jvmMemoryPool.getOldGenMemoryUsage();
		System.out.println(oldspaceMemoryUsage);
	}

}
